//
//  ShopViewController.m
//  1243
//
//  Created by 杨森 on 16/4/13.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "ShopViewController.h"
#import "Masonry.h"
#import "NetWorkTools.h"
#import "ShoeBagDressViewController.h"
#import "SweepViewController.h"
#import "ErWeiMaViewController.h"
#import "JudgeUserLogInTool.h"
#import "ShopCartViewController.h"
#import "NetWorkTools.h"
#import "rightNewShopTableViewCell.h"
#import "LoginViewController.h"
#import "ShopOneCollectionViewCell.h"
#import "CentreCollectionViewCell.h"
#import "BaseNavController.h"
#import "ShopViewCellCollectionViewCell.h"
#import "ShopMainViewController.h"
#define TableViewHeaderHeight [[UIScreen mainScreen] bounds].size.height/5

@interface ShopViewController ()<UITableViewDelegate,UITableViewDataSource,rightNewShopDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
{
    NSString *nameStr;
    NSMutableArray *collArr;
    NSInteger index;
    UIButton *sysBtn;
    UILabel *label;
    UIImageView *topImage;
    NSString *imageStr;
}
@property(nonatomic,strong)UITableView *leftTableView;
@property(nonatomic,strong)UITableView *rightTableView;

@property( nonatomic,strong)UICollectionView *centreCollectionView;
@property(nonatomic,strong)UICollectionViewFlowLayout *flowLayout;
@property(nonatomic,strong)NSArray *leftArray;
@property(nonatomic,strong)NSArray *rightArray;


@property(nonatomic)NSIndexPath *leftIndex;

@end

@implementation ShopViewController

static NSString * const reuseIdentifier = @"centreCollectionCell";

- (NSArray *)rightArray
{
    if (!_rightArray) {
        _rightArray = [[NSArray alloc] init];
    }
    return _rightArray;
}

- (NSArray *)leftArray
{
    if (!_leftArray) {
        _leftArray = [[NSArray alloc] init];
    }
    return _leftArray;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

//    [self setupDefaultData];
    index = 1;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    

    
    [self addTableView];
    [self setNavBarItem];
    UIButton *shopCart = [[UIButton alloc] init];
    [shopCart setFrame:CGRectMake(WIDTH - 60, HEIGHT - 170, 30, 30)];
    [shopCart setImage:[UIImage imageNamed:@"gouwuche"] forState:UIControlStateNormal];
    [shopCart addTarget:self action:@selector(clickShopCart) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:shopCart];
    
    [self loadLeftTableViewData];
}

- (void)clickShopCart {
//    NSLog(@"...");
    if ([JudgeUserLogInTool JudgeUserLonInStatus]) {
        
        [self pushForm:self.navigationController pushToAndHidden:[[ShopCartViewController alloc] init]];
    }else{
        
        LoginViewController *a = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:[NSBundle mainBundle]];
        BaseNavController *baseNav = [[BaseNavController alloc] initWithRootViewController:a];
        [self presentViewController:baseNav animated:YES completion:nil];

    }
}

- (void)setupDefaultData
{
    NSIndexPath *firstIndex = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.leftTableView selectRowAtIndexPath:firstIndex animated:YES scrollPosition:UITableViewScrollPositionTop];
    
}


- (void)addTableView
{
    collArr = [NSMutableArray array];
    
#warning 测试
//    [self loadMerchant];
    self.view.backgroundColor = BACKGROUND_COLOR;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    CGFloat leftViewW;
    
    if (WIDTH == 320) {
        leftViewW = WEITH/6 *2;
    } else {
        leftViewW= 110;
    }
    
    self.leftTableView = [[UITableView alloc] init];
    self.leftTableView.showsVerticalScrollIndicator = NO;
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;


    CGFloat margin = 10;
    CGFloat collectViewW = WEITH - leftViewW;
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
    flowlayout.itemSize = CGSizeMake(collectViewW/3 - margin ,HEIGHT/6);
    flowlayout.minimumLineSpacing = 10;
    flowlayout.minimumInteritemSpacing = 0;
    flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    UICollectionView * ShopCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, collectViewW, HEIGHT) collectionViewLayout:flowlayout];
    
    self.centreCollectionView = ShopCollectionView;
    self.centreCollectionView.delegate = self;
    self.centreCollectionView.dataSource = self;
    self.centreCollectionView.backgroundColor = BACKGROUND_COLOR;
    self.centreCollectionView.mj_footer =  [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData:)];
    self.centreCollectionView.backgroundColor = [UIColor whiteColor];
    self.centreCollectionView.scrollEnabled = YES;
//    [self.centreCollectionView registerNib:[UINib nibWithNibName:@"CentreCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:reuseIdentifier];

    //注册表头
    [self.centreCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    
     [self.centreCollectionView registerNib:[UINib nibWithNibName:@"ShopViewCellCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ShopViewCellCollectionViewCell"];
    //  ShopViewCellCollectionViewCell

    [self.view addSubview:self.leftTableView];
    [self.view addSubview:self.centreCollectionView];
    

    
    [self.leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.view.mas_left);
        make.top.mas_equalTo(self.view.mas_top);
        make.bottom.mas_equalTo(self.view.mas_bottom);
        make.width.mas_equalTo(leftViewW);
    }];
    
    [self.centreCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.leftTableView.mas_right);
        make.top.mas_equalTo(self.view.mas_top);
        make.bottom.mas_equalTo(self.view.mas_bottom);
        make.right.mas_equalTo(self.view.mas_right);
    }];
//    sysBtn= [UIButton buttonWithType:UIButtonTypeCustom];
//    [sysBtn setImage:[UIImage imageNamed:@"bot_1"] forState:UIControlStateNormal];
//    [self.view addSubview:sysBtn];
//    [sysBtn addTarget:self action:@selector(sysBtnAction) forControlEvents:UIControlEventTouchUpInside];
//    [sysBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.left.mas_equalTo(self.leftTableView.mas_right);
//        make.top.mas_equalTo(self.view.mas_top);
//        make.bottom.mas_equalTo(self.view.mas_bottom);
//        make.right.mas_equalTo(self.view.mas_right);
//    }];
    label = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 200, 50)];
    [self.centreCollectionView addSubview:label];
    label.text = @"暂无商品";
    label.textAlignment = NSTextAlignmentCenter;
    label.hidden = YES;
}

- (void)sysBtnAction{
    ShoeBagDressViewController * shoes = [[ShoeBagDressViewController alloc] init];
    shoes.payIndex = 0;
    [self pushForm:self.navigationController pushToAndHidden:shoes];

    
    
    
}
#pragma mark >>>>>>tableView dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.leftArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *shopLeftCell = @"ShopLeftCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:shopLeftCell];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:shopLeftCell];
        //            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.text = [self.leftArray[indexPath.row] objectForKey:@"Name"];
    cell.textLabel.highlightedTextColor = [UIColor redColor];
    cell.textLabel.font = [UIFont systemFontOfSize:12];
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:241/255.0 green:242/255.0 blue:245/255.0 alpha:1];
    
    return cell;

}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
//    if (section == 0) {
//        return 0;
//    }
    return collArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
#warning collectionCell
    ShopViewCellCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ShopViewCellCollectionViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.label.text = collArr[indexPath.item][@"Title"];
//    NSLog(@"%@",collArr[indexPath.item][@"Title"]);
    NSString *URLString = @"http://120.76.162.124:8083";
    NSString *picture = [collArr[indexPath.item] objectForKey:@"PictureURL"];
    NSString *PicString = [URLString stringByAppendingString:picture];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:PicString] placeholderImage:[UIImage imageNamed:@"dress.png"]];
//    NSLog(@"%@",PicString);
    
    
    NSArray *arr =[ collArr[indexPath.row][@"Title"]  componentsSeparatedByString:@"/"];
    NSArray *arr1 =[ collArr[indexPath.row][@"Title"]  componentsSeparatedByString:@"（"];
    
    if (arr.count >= 3) {
          cell.label.text = arr[0];
    }else if (arr1.count >=  2){
        cell.label.text = arr1[0];
    }else{
        cell.label.text = collArr[indexPath.row][@"Title"];
    }
  
    return cell;
}

#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    ShoeBagDressViewController * shoes = [[ShoeBagDressViewController alloc] init];
//   
//    shoes.payIndex = 0;
//    [self pushForm:self.navigationController pushToAndHidden:shoes];

//    NSLog(@"%zd",indexPath.row);
    
    ShopMainViewController *shopMainVC = [[ShopMainViewController alloc] init];
    shopMainVC.xingYingShopID = [collArr[indexPath.row] objectForKey:@"Id"];
//    shopMainVC.str = self.str;
//    [self.navigationController pushViewController:shopMainVC animated:YES];
     [self pushForm:self.navigationController pushToAndHidden:shopMainVC];

}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5,10,0,10);
    
}

#pragma mark---加载UICollectionView表头
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
#warning 头部
    UICollectionReusableView *reusableView = nil;
    
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) { // header

            reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
            CGFloat margin = 10;
            UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.centreCollectionView.width, TableViewHeaderHeight)];
            bgView.backgroundColor = BACKGROUND_COLOR;
            [reusableView addSubview:bgView];
            
            topImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"shopStroe_03"]];
            topImage.frame = CGRectMake(margin,-10, self.centreCollectionView.width - margin*2, TableViewHeaderHeight);
            [bgView addSubview:topImage];
            topImage.contentMode = UIViewContentModeScaleAspectFit;
            [topImage sd_setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"shopStroe_03"]];
            
            
            return reusableView;
        }
    
    return nil;
    
}

#pragma mark >>>>> tableView  delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

        [self.leftTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        
        [self loadRightTableViewData:[self.leftArray[indexPath.row] objectForKey:@"Id"]];
        
        [self loadMerchant:[self.leftArray[indexPath.row] objectForKey:@"Name"]];
    [self loadTopImage:[self.leftArray[indexPath.row] objectForKey:@"Name"]];
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        return 45;
}


 //header组头大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{

    return CGSizeMake(self.centreCollectionView.width, TableViewHeaderHeight);
}



#pragma mark>>>>>>导航栏
- (void)setNavBarItem {
       self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"nav_1"] highImage:[UIImage imageNamed:@"nav_1"] target:self action:@selector(saoYiSaoBtn) imageEdgeInsets:UIEdgeInsetsMake(0, -20, 15, -35) titleEdgeInsets:UIEdgeInsetsMake(20, -50, 0, 0) title:@"扫一扫"];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"nav_3"] highImage:[UIImage imageNamed:@"nav_3"] target:self action:@selector(fuKuanBtn) imageEdgeInsets:UIEdgeInsetsMake(0, 35, 15, -35) titleEdgeInsets:UIEdgeInsetsMake(20, 20, 0, 0) title:@"收款"];
    
    CGRect frame;
    if (WIDTH == 320) {
        frame = CGRectMake(-25, 0, 200, 30);
    } else {
        frame = CGRectMake(0, 0, 200, 30);
    }
    
    UIView *view = [[UIView alloc] initWithFrame:frame];
    
    UITextField *searchFeild = [[UITextField alloc] initWithFrame:frame];
    searchFeild.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入商家或者商品名称" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    searchFeild.textColor = [UIColor redColor];
    searchFeild.font = [UIFont systemFontOfSize:14];
    searchFeild.layer.cornerRadius = searchFeild.frame.size.height/2;
    searchFeild.layer.masksToBounds = YES;
    searchFeild.enabled = NO;
    searchFeild.layer.borderWidth = 1;
    searchFeild.layer.borderColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1].CGColor;
    [self setLeftViewWithTextField:searchFeild imageName:@"nav_2"];
    [view addSubview:searchFeild];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = searchFeild.frame;
    [searchBtn addTarget:self action:@selector(searchBut) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:searchBtn];
    
    self.navigationItem.titleView = view;
}

- (void)searchBut {
//    NSLog(@"...");
}

- (void)saoYiSaoBtn {
    if ([JudgeUserLogInTool  JudgeUserLonInStatus]) {
        SweepViewController *a = [[SweepViewController alloc] init];
        [self pushForm:self.navigationController pushToAndHidden:a];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        
        [alert show];
        
    }
    
}

- (void)fuKuanBtn {
    if ([JudgeUserLogInTool  JudgeUserLonInStatus]) {
        ErWeiMaViewController *a = [[ErWeiMaViewController alloc] init];
        [self pushForm:self.navigationController pushToAndHidden:a];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        
        [alert show];
        
    }
    
}

//tabBar 隐藏
- (void)pushForm:(UINavigationController *)pushForm pushToAndHidden:(UIViewController *)pushToVC
{
    [pushToVC setHidesBottomBarWhenPushed:YES];
    [pushForm pushViewController:pushToVC animated:YES];
    
}

-(void)setLeftViewWithTextField:(UITextField *)textField imageName:(NSString *)imageName{
    
    UIImageView *rightView = [[UIImageView alloc]init];
    
    rightView.image = [UIImage imageNamed:imageName];
    rightView.frame = CGRectMake(0, 0, CGRectGetHeight(textField.frame), CGRectGetHeight(textField.frame));
    rightView.contentMode = UIViewContentModeCenter;
    
    textField.leftView = rightView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.backgroundColor = [UIColor blackColor];
    textField.alpha = 0.25;
}

- (void)loadLeftTableViewData {
    NSDictionary *params = @{
                             @"ParentSortId":@"0"
                             };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"PRODUCTCLASSQUERY" completeBlock:^(id object) {
        
        
        NSString *string = [object objectForKey:@"BackData"];
        
        self.leftArray = [NetWorkTools arrayWithJsonString:string];
        
//        NSLog(@"leftArray%@",self.leftArray);
        [self loadMerchant:[self.leftArray[0] objectForKey:@"Name"]];
        [self loadTopImage:[self.leftArray[0] objectForKey:@"Name"]];
        nameStr =[self.leftArray[0] objectForKey:@"Name"];
        [self.leftTableView reloadData];
        
//        NSLog(@"%@",object)
    }];
}

- (void)loadRightTableViewData:(NSString *)ParentId {
    
    
    NSDictionary *params = @{
                             @"ParentSortId":[NSString stringWithFormat:@"%@",ParentId],
                             @"PageIndex":@"1",
                             @"PageSize":@"10"
                             };

    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"PRODUCTCLASSQUERY" completeBlock:^(id object) {
//        NSLog(@"%@",object);
        NSString *string = [object objectForKey:@"BackData"];
        self.rightArray = [NetWorkTools arrayWithJsonString:string];
//        NSLog(@"rightArrayrightArray%@",self.rightArray);
       
    }];
}


- (void)loadMerchant:(NSString *)name {
    
    NSDictionary *dict = @{
                           @"SortName": name,
                           @"PageIndex": @"1",
                           @"PageSize":@"10",
                           @"Position":@(0)
                           };
    nameStr = name;
    [collArr removeAllObjects];
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"PRODUCTLISTQUERY" completeBlock:^(id object) {
//        NSLog(@"id%@",object[@"Id"]);
//        NSLog(@"Message%@",object[@"Message"]);
        NSDictionary *dic = [NetWorkTools dictionaryWithJsonString:object[@"BackData"]];
        NSArray *ar = dic[@"ds"];
//        NSLog(@"objectobject%@",ar);
        
        for (NSDictionary *dic in ar) {
            [collArr addObject:dic];
        }
//        NSLog(@"collArr%@",collArr);
        [self.centreCollectionView reloadData];
        if ([[NSString stringWithFormat:@"%@",object[@"Id"]] isEqualToString:@"1"]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂无商品" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
            label.hidden = NO;
        }else{
            label.hidden = YES;
        }
        
        
    }];
    
    
}


- (void)loadTopImage:(NSString *)str{
#warning 头部图片
    NSDictionary *params = @{
                             @"SortName":str
                             };
    
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"QUERYSORTPICBYSORTNAME" completeBlock:^(id object) {
        NSDictionary *dic = [NetWorkTools dictionaryWithJsonString:object[@"BackData"]];
        NSString *str = dic[@"ds"][0][@"SortPic"];
        
        NSString *URLString = @"http://120.76.162.124:8083/";
//        NSString *picture = [collArr[indexPath.item] objectForKey:@"PictureURL"];
        
//        NSLog(@"strstr%@",str);
        
        
        if ([str isEqual:[NSNull null]]) {
            return ;
        }
        NSString *PicString = [URLString stringByAppendingString:str];
        imageStr = PicString;
        [self.centreCollectionView reloadData];
        [self.centreCollectionView reloadInputViews];
        
    //    [topImage sd_setImageWithURL:[NSURL URLWithString:PicString] placeholderImage:[UIImage imageNamed:@"dress.png"]];
     
    }];
}

- (void)loadNewData:(NSString *)str{
    
    if (nameStr.length == 0) {
        return;
    }
    
    NSDictionary *dict = @{
                           @"SortName": nameStr,
                           @"PageIndex": [NSString stringWithFormat:@"%ld",(long)index],
                           @"PageSize":@"10",
                           @"Position":@(0)
                           };
    
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"PRODUCTLISTQUERY" completeBlock:^(id object) {
        NSDictionary *dic = [NetWorkTools dictionaryWithJsonString:object[@"BackData"]];
        NSArray *ar = dic[@"ds"];
        for (NSDictionary *dic in ar) {
            [collArr addObject:dic];
        }
//        NSLog(@"collArr%@",collArr);
        [self.centreCollectionView reloadData];
    }];
    
    index ++;
    
}

@end
